package com.example.app3_1;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import androidx.appcompat.app.AppCompatActivity;

public class InterestSelectionActivity extends AppCompatActivity {
    private CheckBox cbReading, cbPhotography, cbPingpong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interest_selection);

        // 初始化复选框
        cbReading = findViewById(R.id.cb_reading);
        cbPhotography = findViewById(R.id.cb_photography);
        cbPingpong = findViewById(R.id.cb_pingpong);

        // 恢复之前的选择
        SharedPreferences prefs = getSharedPreferences("UserData", MODE_PRIVATE);
        String savedInterest = prefs.getString("interest", "");
        if (savedInterest.contains("阅读")) cbReading.setChecked(true);
        if (savedInterest.contains("摄影")) cbPhotography.setChecked(true);
        if (savedInterest.contains("乒乓球")) cbPingpong.setChecked(true);

        // 返回按钮
        Button btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> {
            finish();
        });

        // 确定按钮
        Button btnConfirm = findViewById(R.id.btn_confirm);
        btnConfirm.setOnClickListener(v -> {
            // 获取选择的兴趣
            StringBuilder selectedInterests = new StringBuilder();
            if (cbReading.isChecked()) {
                selectedInterests.append("阅读");
            }
            if (cbPhotography.isChecked()) {
                if (selectedInterests.length() > 0) {
                    selectedInterests.append(",");
                }
                selectedInterests.append("摄影");
            }
            if (cbPingpong.isChecked()) {
                if (selectedInterests.length() > 0) {
                    selectedInterests.append(",");
                }
                selectedInterests.append("乒乓球");
            }

            // 如果没有选择任何兴趣
            if (selectedInterests.length() == 0) {
                selectedInterests.append("无");
            }

            // 保存选择
            SharedPreferences.Editor editor = getSharedPreferences("UserData", MODE_PRIVATE).edit();
            editor.putString("interest", selectedInterests.toString());
            editor.apply();

            // 返回结果
            Intent resultIntent = new Intent();
            resultIntent.putExtra("interest", selectedInterests.toString());
            setResult(RESULT_OK, resultIntent);
            finish();
        });
    }
}